home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / jabber / tlslitestream.pyo (.txt) < prev   
Python Compiled Bytecode  |  2008-10-13  |  13KB  |  376 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. from __future__ import with_statement
  5. from pyxmpp import resolver
  6. from pyxmpp.exceptions import TLSError as XMPPTLSError
  7. from pyxmpp.jabber.clientstream import LegacyClientStream
  8. import util
  9. import common
  10. from common import netcall, profile
  11. from threading import currentThread
  12. import traceback
  13. import sys
  14. import time
  15. import Queue
  16. import logging
  17. import socket
  18. import threadstream
  19.  
  20. try:
  21.     from tlslite.api import TLSError, TLSConnection, TLSAsyncDispatcherMixIn, TLSLocalAlert
  22.     tls_available = 1
  23. except ImportError:
  24.     tls_available = 0
  25.  
  26. log = logging.getLogger('tlslitestream')
  27. outdebug = logging.getLogger('tlslitestream.out').debug
  28. outdebug_s = getattr(logging.getLogger('tlslitestream.out'), 'debug_s', outdebug)
  29. indebug = logging.getLogger('tlslitestream.in').debug
  30. indebug_s = getattr(logging.getLogger('tlslitestream.in'), 'debug_s', outdebug)
  31.  
  32. class AsyncStreamSocket(common.socket):
  33.     
  34.     def __init__(self, sock, collect, on_close, on_error, on_connect, **k):
  35.         self.socket = None
  36.         self.term = 0
  37.         self.tls = None
  38.         self._collector = collect
  39.         self._logger = logging.getLogger(type(self).__name__)
  40.         self.on_close = util.Delegate()
  41.         self.on_close += on_close
  42.         self.on_error = util.Delegate()
  43.         self.on_error += on_error
  44.         self.on_connect = util.Delegate()
  45.         self.on_connect += on_connect
  46.         self.lastbuffer = ''
  47.         self._closed = False
  48.         common.socket.__init__(self, sock)
  49.         self.set_terminator(self.term)
  50.         self.killed = False
  51.  
  52.     
  53.     def collect_incoming_data(self, data):
  54.         self._collector(data)
  55.  
  56.     
  57.     def found_terminator(self):
  58.         self.set_terminator(self.term)
  59.  
  60.     
  61.     def handle_connect(self):
  62.         self._logger.info('handle_connect')
  63.         common.socket.handle_connect(self)
  64.         self.on_connect[:] = util.Delegate([])
  65.         on_connect = util.Delegate(self.on_connect[:])
  66.         on_connect()
  67.  
  68.     
  69.     def handle_error(self, e, force_close = False):
  70.         self.killed = True
  71.         if not force_close and self._closed:
  72.             return None
  73.         
  74.         self._closed = True
  75.         self._logger.info('handle_error: %r', e)
  76.         self.on_error[:] = util.Delegate([])
  77.         on_error = util.Delegate(self.on_error[:])
  78.         on_error()
  79.         self.clear_delegates()
  80.         if force_close:
  81.             self.close()
  82.         
  83.         common.socket.handle_error(self, e)
  84.         if not force_close:
  85.             self.close()
  86.         
  87.  
  88.     
  89.     def handle_expt(self):
  90.         self.handle_error(Exception('OOB Data'), force_close = True)
  91.  
  92.     
  93.     def handle_close(self):
  94.         if self._closed:
  95.             return None
  96.         
  97.         self._closed = True
  98.         self._logger.info('handle_close')
  99.         self.close()
  100.         common.socket.handle_close(self)
  101.         on_close = util.Delegate(self.on_close[:])
  102.         self.on_close[:] = util.Delegate()
  103.         self.clear_delegates()
  104.         if not self.killed:
  105.             on_close()
  106.         
  107.  
  108.     
  109.     def clear_delegates(self):
  110.         del self.on_close[:]
  111.         del self.on_error[:]
  112.         del self.on_connect[:]
  113.         
  114.         def should_not_be_called(*a, **k):
  115.             raise AssertionError('This function should not have been called!')
  116.  
  117.         self.on_close += should_not_be_called
  118.         self.on_error += should_not_be_called
  119.         self.on_connect += should_not_be_called
  120.  
  121.     
  122.     def fileno(self):
  123.         if self.socket is not None:
  124.             return self.socket.fileno()
  125.         else:
  126.             return -1
  127.  
  128.  
  129. if tls_available:
  130.     
  131.     class TLSLiteStreamSocket(TLSAsyncDispatcherMixIn, AsyncStreamSocket):
  132.         ac_in_buffer_size = 16384
  133.         
  134.         def __init__(self, sock, *a, **k):
  135.             AsyncStreamSocket.__init__(self, sock, *a, **k)
  136.             TLSAsyncDispatcherMixIn.__init__(self, sock)
  137.             self._logger = logging.getLogger(type(self).__name__)
  138.  
  139.         
  140.         def setup_ssl(self, callback = None):
  141.             self._logger.info('Setting up SSL')
  142.             self._set_tls_opts((3, 0))
  143.             self._start_tls()
  144.  
  145.         setup_ssl = util.callsback(setup_ssl)
  146.         
  147.         def setup_tls(self, callback = None):
  148.             self._logger.info('Setting up TLS')
  149.             self._set_tls_opts((3, 1))
  150.             self._start_tls()
  151.  
  152.         setup_tls = util.callsback(setup_tls)
  153.         
  154.         def _set_tls_opts(self, version):
  155.             self.tlsConnection.version = version
  156.             self.tlsConnection.ignoreAbruptClose = True
  157.             self.tlsConnection.closeSocket = True
  158.  
  159.         
  160.         def _start_tls(self):
  161.             self.setHandshakeOp(self.tlsConnection.handshakeClientCert(async = True))
  162.  
  163.         
  164.         def close(self):
  165.             
  166.             try:
  167.                 TLSAsyncDispatcherMixIn.close(self)
  168.             except Exception:
  169.                 e = None
  170.                 traceback.print_exc()
  171.                 log.error('Error trying to shut down TLSConnection. Un-cleanly closing socket. (the error was: %r)', e)
  172.                 AsyncStreamSocket.close(self)
  173.  
  174.  
  175.         
  176.         def handle_error(self, e, force_close = False):
  177.             if self._closed:
  178.                 return None
  179.             
  180.             
  181.             try:
  182.                 raise e
  183.             except TLSLocalAlert:
  184.                 if getattr(e, 'errorStr', None) is not None:
  185.                     e.verbose = False
  186.                 
  187.             except:
  188.                 getattr(e, 'errorStr', None) is not None
  189.  
  190.             AsyncStreamSocket.handle_error(self, e, force_close = force_close)
  191.  
  192.  
  193. else:
  194.     log.error("Defining a stub for TLSLiteStreamSocket, but I really shouldn't be here...")
  195.     
  196.     class TLSLiteStreamSocket(AsyncStreamSocket):
  197.         pass
  198.  
  199.  
  200. class TLSLiteStream(threadstream.ThreadStream):
  201.     tls_available = tls_available
  202.     
  203.     def __init__(self, *a, **k):
  204.         threadstream.ThreadStream.__init__(self, *a, **k)
  205.         if self.owner.do_ssl:
  206.             pass
  207.         self.do_ssl = self.tls_available
  208.         if self.tls_settings and any(self.tls_settings.__dict__.values()):
  209.             pass
  210.         self.use_tls = self.tls_available
  211.         self._socket_class = AsyncStreamSocket
  212.         log.info('using _socket_class %r', self._socket_class)
  213.  
  214.     
  215.     def _determine_conn_info(self, server, port):
  216.         if not server:
  217.             server = self.server
  218.         
  219.         if not port:
  220.             port = self.port
  221.         
  222.         if server:
  223.             service = None
  224.         else:
  225.             service = 'xmpp-client'
  226.         if port is None:
  227.             port = 5222
  228.         
  229.         if server is None:
  230.             server = self.my_jid.domain
  231.         
  232.         self.me = self.my_jid
  233.         return (server, port, service)
  234.  
  235.     
  236.     def endpoint_generator(self, server, port, service = None, to = None):
  237.         if to is None:
  238.             to = str(server)
  239.         
  240.         addrs = []
  241.         if service is not None:
  242.             
  243.             try:
  244.                 self.state_change('resolving srv', (server, service))
  245.                 if not resolver.resolve_srv(server, service):
  246.                     pass
  247.                 addrs = []
  248.             except Exception:
  249.                 e = None
  250.                 log.debug('Failed to resolve %r: %r', (server, service), e)
  251.             except:
  252.                 None<EXCEPTION MATCH>Exception
  253.             
  254.  
  255.         None<EXCEPTION MATCH>Exception
  256.         addrs.append((server, port))
  257.         for address, port in addrs:
  258.             if type(address) not in (str, unicode):
  259.                 continue
  260.             
  261.             self.state_change('resolving', address)
  262.             
  263.             try:
  264.                 resolved = resolver.getaddrinfo(address, port, 0, socket.SOCK_STREAM)
  265.             except Exception:
  266.                 resolved = []
  267.  
  268.             resolved.append((2, 1, 0, '_unused', (address, port)))
  269.             for sock_info in resolved:
  270.                 yield sock_info
  271.             
  272.         
  273.  
  274.     
  275.     def _connect1(self, server = None, port = None):
  276.         outdebug('_connect1')
  277.         (server, port, service) = self._determine_conn_info(server, port)
  278.         if getattr(self, '_endpoints', None) is None:
  279.             self._endpoints = self.endpoint_generator(server, port, service, self.my_jid.domain)
  280.         elif getattr(self, '_endpoints', None) is False:
  281.             return None
  282.         
  283.         if getattr(self, 'socket', None) is not None:
  284.             self.socket.close()
  285.             self.socket = None
  286.         
  287.         
  288.         try:
  289.             endpoint = self._endpoints.next()
  290.         except StopIteration:
  291.             if self.socket is not None:
  292.                 self.socket.close()
  293.                 self.socket = None
  294.             
  295.             self._endpoints = None
  296.             log.info('No more endpoints to try.')
  297.             return self.owner.connect_attempt_failed()
  298.  
  299.         self.socket = self._socket_class(sock = False, collect = self._feed_reader, on_close = self.closed, on_error = self.closed_dead, on_connect = (lambda : pass), ssl = self.do_ssl)
  300.         (family, socktype, proto, _unused, sockaddr) = endpoint
  301.         (addr, port) = sockaddr
  302.         self.socket.create_socket(family, socktype)
  303.         self.socket.socket.settimeout(2)
  304.         self.state_change('connecting', sockaddr)
  305.         
  306.         def setup_success():
  307.             self.addr = addr
  308.             self.port = port
  309.             self._connect_socket(self.socket, self.my_jid.domain)
  310.             self._endpoints.close()
  311.             self._endpoints = False
  312.             self.last_keepalive = time.time()
  313.             self.owner.lock.__enter__()
  314.             
  315.             try:
  316.                 if self.owner.connect_killed == True:
  317.                     raise FatalStreamError('Cannot connect')
  318.             finally:
  319.                 pass
  320.  
  321.  
  322.         
  323.         def connect_fail(e = (None, (None, None, None), None)):
  324.             log.error('connection to %r failed: %r', (addr, port), e)
  325.             self._connect1()
  326.  
  327.         
  328.         def connect_success():
  329.             log.info('connection to %r succeeded', (addr, port))
  330.             self.state_change('connected', sockaddr)
  331.             if self.do_ssl:
  332.                 log.debug('\tsetting up socket SSL')
  333.                 self.setup_ssl(success = setup_success, error = connect_fail)
  334.             else:
  335.                 log.debug('\tinitializing stream connection')
  336.                 setup_success()
  337.  
  338.         self.socket.on_connect += connect_success
  339.         self.socket.connect(sockaddr, error = connect_fail)
  340.  
  341.     
  342.     def change_sock_type(self, new_cls):
  343.         sck = self.socket.socket
  344.         self.socket.del_channel()
  345.         oldsck = self.socket
  346.         oldsck.socket = None
  347.         self.socket = new_cls(sock = sck, collect = oldsck._collector, on_close = oldsck.on_close, on_error = oldsck.on_error, on_connect = oldsck.on_connect, ssl = True)
  348.         self.socket.on_connect.extend(oldsck.on_connect)
  349.         self.socket.add_channel()
  350.  
  351.     
  352.     def setup_ssl(self, callback = None):
  353.         self.change_sock_type(TLSLiteStreamSocket)
  354.         self.socket.on_connect += callback.success
  355.         self.socket.on_error += callback.error
  356.         self.socket.setup_ssl()
  357.  
  358.     setup_ssl = util.callsback(setup_ssl)
  359.     
  360.     def _make_tls_connection(self, callback = None):
  361.         self.change_sock_type(TLSLiteStreamSocket)
  362.         self.socket.on_connect += callback.success
  363.         (self.socket.on_connect,) += (lambda : self.state_change('tls connected', self.peer))
  364.         self.socket.on_error += callback.error
  365.         self.tls = self.socket
  366.         self.state_change('tls connecting', self.peer)
  367.         self.socket.setup_tls()
  368.  
  369.     _make_tls_connection = util.callsback(_make_tls_connection)
  370.     
  371.     def _connect_socket(self, sock, to = None):
  372.         logging.getLogger('ThreadStream').debug('connecting')
  373.         (None, None, netcall)((lambda : LegacyClientStream._connect_socket(self, sock, to)))
  374.  
  375.  
  376.